﻿using System.Linq;
using Zj.HttpCodeDemo.Domain.Entities;
using Zj.HttpCodeDemo.Repository.Models;
using Z.EntityFramework.Plus;
using System.Linq.Expressions;
using System;

namespace Zj.HttpCodeDemo.ConsoleApp.Samples
{
    internal class EntityFrameworkExtensionSample
    {
        internal static void Sample()
        {
            //using (var ctx = new TodoDbContext())
            //{
            //    ctx.Tag.Where(t => t.Name.Equals("散户之家"))
            //       .Update(t => new Tag() { Name = "散户之家01" }); //Batch update.

            //    ctx.Tag.Where(t => t.Name.Equals("散户之家01"))
            //       .Delete();//Batch delete.

            //    var tags = ctx.Tag.OrderBy(t => t.Name);
            //    var count = tags.DeferredCount().FutureValue();
            //    var list = tags.Skip(2).Take(2)
            //        .Future();//EntityFramework optimize.
            //    ctx.SaveChanges();
            //}
            var count = BatchUpdate<Tag>(t => t.Name.Equals("悟空啊悟空"), t => new Tag() { Name = "悟空" });
            var count_ = BatchDelete<Tag>(t => t.Name.Equals("悟空"));
        }

        /// <summary>
        /// Batch delete.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        private static int BatchDelete<TEntity>(Expression<Func<TEntity, bool>> whereExp)
            where TEntity : class, new()
        {
            using (var ctx = new TodoDbContext())
            {
                return ctx.Set<TEntity>().Where(whereExp)
                     .Delete();
            }
        }

        /// <summary>
        /// BatchUpdate.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="whereExp"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        private static int BatchUpdate<TEntity>(Expression<Func<TEntity, bool>> whereExp, Expression<Func<TEntity, TEntity>> updateExp)
             where TEntity : class, new()
        {
            using (var ctx = new TodoDbContext())
            {
                return ctx.Set<TEntity>().Where(whereExp)
                     .Update(updateExp);
            }
        }
    }
}